package com.hanbang.mrcm_merchant.announce;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.hanbang.mrcm_merchant.R;
import com.hanbang.mrcm_merchant.application.MyApplication;
import com.hanbang.mrcm_merchant.base.BaseActivity;
import com.hanbang.mrcm_merchant.bean.UserInforData;
import com.hanbang.mrcm_merchant.else_module.LogInActivity;
import com.hanbang.mrcm_merchant.else_module.RegisterActivity;
import com.hanbang.mrcm_merchant.myview.MyDialog;
import com.hanbang.mrcm_merchant.myview.MyDialog.MODE;
import com.hanbang.mrcm_merchant.myview.MyDialog.OnClickCallback;
import com.hanbang.mrcm_merchant.photo.ClipLayout;
import com.hanbang.mrcm_merchant.photo.ClipPhotoActivity;
import com.hanbang.mrcm_merchant.utils.EditHelper;
import com.hanbang.mrcm_merchant.utils.HttpInterfaces;
import com.hanbang.mrcm_merchant.utils.JsonHelper;
import com.hanbang.mrcm_merchant.utils.MyLog;
import com.hanbang.mrcm_merchant.utils.MyRequestCallBack;
import com.hanbang.mrcm_merchant.utils.MySharedPreferences;
import com.hanbang.mrcm_merchant.utils.MyToast;
import com.hanbang.mrcm_merchant.utils.SystemTools;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class PersonalActivity extends BaseActivity implements OnClickListener {
	private ImageView alter_logo;
	// 拍完照存放的名称
	private String camera = "capture.jpg";
	private EditHelper editHelper = new EditHelper(this);
	// 验证码按钮倒计时 总时长和间隔时长
	private long totalTime = 60000, intervalTime = 1000;
	// logo本地路径
	private String logopath = "";
	private TextView alter_code_button;
	private EditText alter_sellerlogin, alter_nice, alter_phone, alter_sms_yzm,
			alter__address;
	private LinearLayout ll_alter_sms_yzm;
	private Button alter_submit;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.personalactivity);
		initView();
		setTheListener();
	}

	private void initView() {
		// TODO Auto-generated method stub
		setTitle(findViewById(R.id.top_bar_title), "个人中心");
		alter_logo = (ImageView) findViewById(R.id.alter_logo);
		ll_alter_sms_yzm = (LinearLayout) findViewById(R.id.ll_alter_sms_yzm);
		alter_code_button = (TextView) findViewById(R.id.alter_user_register_auth_code_button);
		alter_sellerlogin = (EditText) findViewById(R.id.alter_sellerlogin);
		alter_nice = (EditText) findViewById(R.id.alter_nice);
		alter_phone = (EditText) findViewById(R.id.alter_phone);
		alter_sms_yzm = (EditText) findViewById(R.id.alter_sms_yzm);
		alter__address = (EditText) findViewById(R.id.alter__address);
		alter_submit = (Button) findViewById(R.id.alter_submit);
		setAlterData();
		editHelper.setEditText(alter_sellerlogin, alter_nice, alter_phone,
				alter__address);
		editHelper.setHintText("请输入正确登录用户名", "请输入商家名称", "请输入手机号", "请输入商家地址");
		editHelper.setHintMinNumber(1, 1, 11, 1);
	}

	private void setAlterData() {
		// TODO Auto-generated method stub
		bitmapUtils.display(alter_logo,
				SystemTools.getHttpFileUrl(userData.getAvatar()));
		alter_sellerlogin.setText(userData.getUser_name());
		alter_nice.setText(userData.getNickname());
		alter_phone.setText(userData.getMobile());
		alter__address.setText(userData.getAddress());
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.alter_logo:
			MyDialog dialog = new MyDialog(PersonalActivity.this,
					R.style.about_me_dialog, MODE.HEAD);
			dialog.setOnClickCallback(new OnClickCallback() {
				@Override
				public void onClick(MyDialog dialog, Object number,
						Object content) {
					// 拍照
					if ((Integer) number == 1) {
						File fDir = new File(MyApplication.picFilepath);
						if (fDir.exists() || fDir.mkdirs()) {
							File cameraFile = new File(fDir, camera);
							if (!cameraFile.exists()) {
								try {
									cameraFile.createNewFile();
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
							Intent intent = new Intent(
									MediaStore.ACTION_IMAGE_CAPTURE);
							intent.putExtra(MediaStore.EXTRA_OUTPUT,
									Uri.fromFile(cameraFile));
							startActivityForResult(intent, 998);
						}
						// 相册选择
					} else if ((Integer) number == 2) {
						// 获取相册
						Intent intent = new Intent();
						intent.setType("image/*");
						intent.setAction(Intent.ACTION_GET_CONTENT);
						intent.putExtra("return-data", true);
						startActivityForResult(intent, 999);
					}
				}
			});

			dialog.show();
			break;
		case R.id.alter_submit:
			String t1 = alter_sellerlogin.getText().toString().trim();
			String t2 = alter_nice.getText().toString().trim();
			String t3 = alter_phone.getText().toString().trim();
			String t4 = alter__address.getText().toString().trim();
			String t5 = alter_sms_yzm.getText().toString().trim();

			if (editHelper.check()) {
				if ((t3.equals(userData.getMobile()))) {

					postAlter(t1, t2, t3, t4, t5, logopath);

				} else {
					ll_alter_sms_yzm.setVisibility(View.VISIBLE);
					alter_code_button.setVisibility(View.VISIBLE);
					if (alter_sms_yzm.equals("")) {
						MyToast.show(PersonalActivity.this, "请输入验证码",
								Toast.LENGTH_SHORT);
					} else {
						postAlter(t1, t2, t3, t4, t5, logopath);
					}
				}
			}
			break;
		case R.id.alter_user_register_auth_code_button:
			sendYZM();
			break;
		default:

			break;
		}
	}

	private void setTheListener() {
		// TODO Auto-generated method stub
		alter_logo.setOnClickListener(this);
		alter_code_button.setOnClickListener(this);
		alter_submit.setOnClickListener(this);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		/*
		 * 相册 resultCode: 正常返回-1 用户后退返回0
		 */

		if (requestCode == 999 && resultCode == -1) {
			Intent intent = new Intent(PersonalActivity.this,
					ClipPhotoActivity.class);
			Uri uri = data.getData();
			intent.putExtra("path",
					SystemTools.getPath(PersonalActivity.this, uri));
			configIntent(intent);
			startActivityForResult(intent, 1000);

		}
		/*
		 * 相片裁剪界面发过来的
		 */
		if (requestCode == 1000 && resultCode == 1000) {
			logopath = data.getStringExtra("path");
			bitmapUtils.display(alter_logo, logopath);
		}
		// 拍照返回的数据
		if (requestCode == 998 && resultCode == -1) {
			Intent intent = new Intent(PersonalActivity.this,
					ClipPhotoActivity.class);
			File fDir = new File(MyApplication.picFilepath);
			if (fDir.exists() || fDir.mkdirs()) {
				File cameraFile = new File(fDir, camera);
				if (cameraFile.exists()) {
					intent.putExtra("path", cameraFile.getPath());
					configIntent(intent);
					startActivityForResult(intent, 1000);
				} else {
					MyToast.show(PersonalActivity.this, "获取照片失败！",
							Toast.LENGTH_SHORT);
				}
			} else {
				MyToast.show(PersonalActivity.this, "获取照片失败！",
						Toast.LENGTH_SHORT);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	};

	private void postAlter(final String t1, final String t2, final String t3,
			final String t4, final String t5, final String logopath2)
			throws IndexOutOfBoundsException {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();

		params.addBodyParameter("action", "seller_update");
		params.addBodyParameter("sellerlogin", userData.getUser_name());
		params.addBodyParameter("password", userData.getPassword());
		params.addBodyParameter("shop", t2);
		params.addBodyParameter("mobile", t3);
		params.addBodyParameter("shopaddress", t4);
		if (!t5.equals("")) {
			params.addBodyParameter("code", t5);
		}
		if (!userData.getUser_name().equals(t1)) {
			params.addBodyParameter("loginupdate", t1);
		}
		if (logopath.equals("")) {
			params.addBodyParameter("sellerlogo", userData.getAvatar());
		} else {
			File f = new File(logopath2);
			if (f.exists()) {
				params.addBodyParameter("sellerlogo", f);
			}
		}

		httpUtils.send(HttpMethod.POST, HttpInterfaces.seller_update, params,
				new MyRequestCallBack<String>(this, "正在注册...") {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							int status = json.getInt("status");
							if (status == 1) {
								MyToast.show(PersonalActivity.this,
										json.getString("msg"),
										Toast.LENGTH_LONG);
								login(t1, userData.getPassword());
							} else {
								MyToast.show(PersonalActivity.this,
										json.getString("msg"),
										Toast.LENGTH_LONG);
							}
						} catch (JSONException e) {
							e.printStackTrace();
							MyToast.show(PersonalActivity.this, "修改失败",
									Toast.LENGTH_LONG);
						}
					}
				});
	}

	private void configIntent(Intent intent) {
		intent.putExtra("borderWidth", 2);
		intent.putExtra("clipPadding", 0);
		intent.putExtra("clipWidth", 1);
		intent.putExtra("clipHeight", 1);
		intent.putExtra("shared", ClipLayout.RECT);
	}

	private void login(String... aa) {
		final ArrayList<String> res = editHelper.getText();
		RequestParams params = new RequestParams();
		params.addBodyParameter("action", "seller_login");
		params.addBodyParameter("user_name", aa[0]);
		params.addBodyParameter("password", aa[1]);
		httpUtils.send(HttpMethod.POST, HttpInterfaces.userLogin, params,
				new MyRequestCallBack<String>(this, null) {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							int status = json.getInt("status");
							if (status == 1) {
								UserInforData userInforData = JsonHelper
										.parseObject(json, UserInforData.class);
								try {
									dbUtils.saveOrUpdate(userInforData);
									// 把id 保存在sp
									MySharedPreferences
											.setSharedPreferencesKeyAndValue(
													PersonalActivity.this,
													MySharedPreferences.USER_DATA,
													"user_id",
													userInforData.getTrade_id());
								} catch (DbException e) {
									e.printStackTrace();
								}
							} else if (status == -100) {
								passwordIsError(true);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
						finish();
					}
				});
	}

	private void sendYZM() throws IndexOutOfBoundsException {
		final ArrayList<String> res = editHelper.getText();
		if (alter_phone.getText().toString().trim() == null
				|| alter_phone.getText().toString().trim().equals("")
				|| alter_phone.getText().toString().trim().length() < 11) {
			MyToast.show(PersonalActivity.this, "请正确输入手机号！", Toast.LENGTH_LONG);
			return;
		}
		Log.e("flfllflffl", HttpInterfaces.seller_register + "&mobile="
				+ alter_phone.getText().toString().trim() + "&type=1");
		httpUtils.send(HttpMethod.GET, HttpInterfaces.send_verify_sms_code
				+ "&mobile=" + alter_phone.getText().toString().trim()
				+ "&type=1", new MyRequestCallBack<String>(this, "正在发送验证码...") {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				super.onSuccess(responseInfo);
				try {
					JSONObject json = new JSONObject(responseInfo.result);
					int status = json.getInt("status");
					if (status == 1) {
						countDownTimer.start();
					}
					MyToast.show(PersonalActivity.this, json.getString("msg"),
							Toast.LENGTH_LONG);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});

	}

	CountDownTimer countDownTimer = new CountDownTimer(totalTime, intervalTime) {
		@Override
		public void onFinish() {// 计时完毕时触发
			alter_code_button.setText("重新发送");
			alter_code_button.setEnabled(true);
			// alter_code_button.setClickable(true);
		}

		@Override
		public void onTick(long currentTime) {// 计时过程显示
			// alter_code_button.setClickable(false);
			alter_code_button.setEnabled(false);
			alter_code_button.setText(currentTime / 1000 + "秒");
		}
	};
}
